package org.duang.lock;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.CloseableUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 在WAIT_TIMEOUT时间内执行完全部方法则不会抛出异常
 * @author laotang
 * https://git-wip-us.apache.org/repos/asf?p=curator.git;a=tree;f=curator-examples/src/main/java/locking;h=c105f8ccfb407aade35b12e7b49405bfb24bc334;hb=HEAD
 */
public class ZkSyncLock {

	private static Logger logger = LoggerFactory.getLogger(ZkSyncLock.class);
	
	private static CuratorFramework curator = null;
	private static final String ROOT_PATH = "/tmp/zookeeper/beauty/locks"; // 根
	private static final long WAIT_TIMEOUT = 5;					// 锁超时(5秒)
	
	public static CuratorFramework getCuratorFramework() {
        if (null == curator) {
            try {
                curator = ZkClientFactory.init();
                if (null != curator) {
                    curator.start();
                    logger.warn("zookeeper curator start success...");
                }
            } catch (Exception e) {
            	logger.warn(e.getMessage(), e);
            }
        }
        
		return curator;
    }
	
	public static String getRootPath(){
		return ROOT_PATH;
	}
	
	public static long getWaitTimeout(){
		return WAIT_TIMEOUT;
	}

	/**
	 * 测试用
	 * @throws Exception
	 */
	public static void lock() throws Exception {
		ExecutorService executService = Executors.newFixedThreadPool(10);
		try {
			for(int i=0; i<10; i++){
				System.out.println("##############################: " + i);
				final long index = i;
				Callable<Void> task = new Callable<Void>(){
					@Override
					public Void call() throws Exception {
						try{
							LockJob job = new LockJob(curator, ROOT_PATH, "lockJob_"+ index);
//							for(int j=0; j<2; j++){
								job.doWork(WAIT_TIMEOUT);
//							}
						} catch(Exception e) {
							e.printStackTrace();
						}
						return null;
					}
				};
				executService.submit(task);
			}
			executService.shutdown();
			executService.awaitTermination(10, TimeUnit.MINUTES);
		} finally {
			CloseableUtils.closeQuietly(curator);
		}
	}
	
	public static void main(String[] args) {
		try{
			lock();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		
	}

}
